import React, { useReducer, useState } from 'react';

const UseReduce = () => {
 /*
  const [count, setCount] = useState(1)
  const addHandler = () => {
    setCount(preState => preState + 1)
  }
  const subHandler = () => {
    setCount(preState => preState - 1)
  }
  */

  /**
   * useReducer 钩子函数
   * @param {function} reducer 整合函数 => 返回值为state新值
   *    reducer执行时收到的参数
   *    @param {any} state 当前最新的state
   *    @param {object} action 在对象中存储dispatch
   * @param {any} initialArg state的初始值
   * @param {} init 
   * 
   * @return {array}
   *    @param {any} state 获取state的值
   *    @param {any} state state修改的派发器，发送操作state的命令，由reducer执行
  */
  const [count, couneDispatch] = useReducer((state, action)=>{
    console.log(state, action.type)
    const stateMap = new Map([
      ['add', state + 1],
      ['sub', state - 1],
      // ['sub', function() { state -= 1 }],
    ]);
    // if(stateMap.has(action.type)){
    //   stateMap.get(action.type)
    // }
    state = stateMap.get(action.type) || state
    return state
  }, 1)
  const addHandler = () => {
    couneDispatch({type: 'add'})
  }
  const subHandler = () => {
    couneDispatch({type: 'sub'})
  }
  return (
    <div>
      <h2>UseReduce</h2>
      <div>
        <button onClick={subHandler}>减少</button>
        {count}
        <button onClick={addHandler}>增加</button>
      </div>
    </div>
  );
};

export default UseReduce;